package com.app.trafficclient;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.app.trafficclient.dianChuanGanQiTiaoZhuanDeZheXianTu.BeanChuanGanQi;
import com.app.trafficclient.dianChuanGanQiTiaoZhuanDeZheXianTu.ZheXianTu;
import com.app.trafficclient.util.UserDao;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class huanJingZhiBiao extends AppCompatActivity implements View.OnClickListener{
      private ImageView imageViewBack;
    private TextView tvTitle;
    private RelativeLayout envirT1L1;
    private TextView envirWendu;
    private RelativeLayout envirT1L2;
    private TextView envirShidu;
    private RelativeLayout envirT1L3;
    private TextView envirGuangZhao;
    private RelativeLayout envirT2L1;
    private TextView envirCO2;
    private RelativeLayout envirT2L2;
    private TextView envirPM;
    private RelativeLayout envirT2L3;
    private TextView envirLuKuang;
    TextView[] textViews;
    UserDao dao ;
    Handler handler;
    static int count = 0 ;
    private static final String TAG = "no";
    private String wenDu1,shiDu1,guangZhao1,co21,pm21,daoLu1;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
 RequestQueue requestQueue;
Boolean aBoolean =true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.environment_pointer);

        initView();
        initListener();
        initData();
        timer();
    }

    private void initData() {


        requestQueue = Volley.newRequestQueue(getApplicationContext());
        sharedPreferences = getSharedPreferences("warmSetting", Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();

        String defaultValue = "";
        if (  sharedPreferences.getInt("flag",0) == 1) {
            wenDu1     = sharedPreferences.getString("wendu",    defaultValue);
            shiDu1     = sharedPreferences.getString("shidu",    defaultValue);
            guangZhao1 = sharedPreferences.getString("guangzhao",defaultValue);
            co21       = sharedPreferences.getString("co2",      defaultValue);
            pm21       = sharedPreferences.getString("pm2",      defaultValue);
            daoLu1     = sharedPreferences.getString("daolu",    defaultValue);
        }
    }

    private void timer() {

        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                sendPost();
                envirLuKuang.setText(  "6" );
            }//handlerMessage

        };//new Handler

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (aBoolean){
                    try {
                        handler.sendEmptyMessage(1);
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    } //timer方法结束



    @Override
    protected void onDestroy() {
        aBoolean = false;
        requestQueue.cancelAll(TAG);
        super.onDestroy();
    }

    private void initListener() {
        imageViewBack.setOnClickListener(this);
        for (int i = 0;i<=5;i++){
            textViews[i].setOnClickListener(this);
        }
    } //initListener

    private void initView() {
        dao=new UserDao(huanJingZhiBiao.this);
        imageViewBack = findViewById(R.id.imageView_back);
        imageViewBack.setImageResource(R.drawable.change);
        tvTitle = findViewById(R.id.tv_title);
        tvTitle.setText("环境指标");

        envirT1L1 = findViewById(R.id.envir_t1_L1); //一行1  ，这是一个布局，为了过阈值，设置颜色 控件在布局里
        envirWendu = findViewById(R.id.envir_wendu);

        envirT1L2 = findViewById(R.id.envir_t1_L2);  //1行2
        envirShidu = findViewById(R.id.envir_shidu);

        envirT1L3 = findViewById(R.id.envir_t1_L3);
        envirGuangZhao = findViewById(R.id.envir_guangZhao);

        envirT2L1 = findViewById(R.id.envir_t2_L1);
        envirCO2 = findViewById(R.id.envir_CO2);

        envirT2L2 = findViewById(R.id.envir_t2_L2);
        envirPM = findViewById(R.id.envir_PM2);

        envirT2L3 = findViewById(R.id.envir_t2_L3);
        envirLuKuang = findViewById(R.id.envir_luKuang);
        textViews = new TextView[]{envirWendu,envirShidu,envirGuangZhao,envirCO2,envirPM,envirLuKuang};
    }

    //传感器跳转折线图
public void newIntent(int index){
        Intent intent = new Intent();
        intent.setClass(huanJingZhiBiao.this,ZheXianTu.class);
        intent.putExtra("index",index);
        startActivity(intent);
}


//发送post请求
public void sendPost(){
    String url ="http://www.wpwh.info/environment/all-sensor";

    Map<String, String> map = new HashMap<String, String>();
    map.put("username", "user1");
//    Log.d("tag1", merchant.toString());
    JSONObject jsonObject = new JSONObject(map);
     final JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d("tag1", "response -> " + response.toString());
                    String string = response.toString();
                    Gson gson = new Gson();
                    BeanChuanGanQi myClass = gson.fromJson(string,BeanChuanGanQi.class);
                   // Log.d("tag1",String.valueOf(myClass.getCo2()));
                    envirCO2.      setText(String.valueOf(myClass.getCo2        ()));
                    envirWendu.    setText(String.valueOf(myClass.getTemperature()));
                    envirShidu.    setText(String.valueOf(myClass.getHumidity   ()));
                    envirGuangZhao.setText(String.valueOf(myClass.getLight      ()));
                    envirPM.       setText(String.valueOf(myClass.getPm         ()));

//                  数据库 存储值  ，值从文本框获取，文本框从传感器
                    int i = dao.Environment(
                        Integer.parseInt( envirWendu    .getText().toString()),
                        Integer.parseInt( envirShidu    .getText().toString()),
                        Integer.parseInt( envirGuangZhao.getText().toString()),
                        Integer.parseInt( envirCO2      .getText().toString()),
                        Integer.parseInt( envirPM       .getText().toString()),
                        Integer.parseInt( envirLuKuang  .getText().toString())
                                           );
//                        if (i>=0){
//                           Toast.makeText(getApplicationContext(),String.valueOf(i),Toast.LENGTH_SHORT).show();
//                        }else{
//                            Toast.makeText(getApplicationContext(),"no",Toast.LENGTH_SHORT).show();
//                        }
                    duib1i();

                }

            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
//                    Log.d("sssss",error.toString());
                }
    });
    jsonRequest.setTag(TAG);
    requestQueue.add(jsonRequest);
}//sendPost


//和阈值对比
    private void duib1i() {
        Cursor cursor = dao.getEnvironment();
        cursor.moveToLast(); //到最后，最新的数值，为了阈值和最新的对比
        if (cursor != null) {
            //从数据库取出，
            int wendu = cursor.getInt(cursor.getColumnIndex("temperature"));
            int shidu = cursor.getInt(cursor.getColumnIndex("humidity"));
            int guangzhao = cursor.getInt(cursor.getColumnIndex("LightIntensity"));
            int co2 = cursor.getInt(cursor.getColumnIndex("co2"));
            int pm2_5 = cursor.getInt(cursor.getColumnIndex("pm2_5"));
            int lukuang = cursor.getInt(cursor.getColumnIndex("roadStatus"));
            //从阈值设置的值 取出来，为了和传感器对比
            if (  sharedPreferences.getInt("flag",0) == 1){
                int values[]    ={wendu,    shidu,    guangzhao,
                        co2,      pm2_5,    lukuang}; //从数据库获取的最新的6个数值
                View views[]    ={envirT1L1,envirT1L2,envirT1L3,
                        envirT2L1,envirT2L2,envirT2L3};//6个布局, 设置红绿用
                String warm[]   ={wenDu1,   shiDu1,   guangZhao1,
                        co21,     pm21,     daoLu1}; //阈值设置的值
                //比对和设置色
                for (int j = 0;j<6;j++){
                    //数据库中存的最新值  大于  阈值
                    if (values[j] >= Integer.parseInt( warm[j]) ) {    //大于设置的值
                        views[j].setBackgroundColor(getResources().getColor(R.color.zhongdu)); //对应的控件  红色
                    }else{
                        views[j].setBackgroundColor(getResources().getColor(R.color.changtong));
                    }//内if
                }
            }// if (  sharedPreferences.getInt("flag",0) == 1)
        }//if (cursor != null)
        cursor.close();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.envir_wendu:newIntent(0);break;
            case R.id.envir_shidu:newIntent(1);break;
            case R.id.envir_guangZhao:newIntent(2);break;
            case R.id.envir_CO2:newIntent(3);break;
            case R.id.envir_PM2:newIntent(4);break;
            case R.id.envir_luKuang:newIntent(5);break;
            case R.id.imageView_back:finish();break;
        }
    }
}//class
